Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

  1. [
  2. [7],
  3. [2, 2, 3]
  4. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  3. Arrays.sort(candidates);
  4. List<List<Integer>> res = new ArrayList<List<Integer>>();
  5. helper(candidates, target, 0, new ArrayList<Integer>(), res);
  6. return res;
  7. }
  8. private void helper(int[] candidates, int target, int index, List<Integer> sol, List<List<Integer>> res) {
  9. if (target == 0) {
  10. res.add(new ArrayList<Integer>(sol));
  11. return;
  12. }
  13. if (target < 0 || index == candidates.length) {
  14. return;
  15. }
  16. for (int i = index; i < candidates.length; i++) {
  17. sol.add(candidates[i]);
  18. helper(candidates, target - candidates[i], i, sol, res);
  19. sol.remove(sol.size() - 1);
  20. }
  21. }
  22. }